//
//  ViewController.m
//  19-homework-homeOfCar
//
//  Created by 王道林 on 16/8/9.
//  Copyright © 2016年 王道林. All rights reserved.
//

#import "ViewController.h"
#import "AllCarTableViewCell.h"
#import "EachCarModel.h"
#import "GroupCarModel.h"
#import "HotTableViewCell.h"
#import "RootClass.h"
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *marrCar;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
//    [self createData];
    
    [self createDataUrl];
    
    [_tableView registerClass:[HotTableViewCell class] forCellReuseIdentifier:@"poolHot"];
    
}
#pragma mark -data
#if 0
- (void)createData
{
    
    _marrCar = [NSMutableArray array];
    // hot的Data
    
    NSString *pathHotBrand = [[NSBundle mainBundle] pathForResource:@"HotBrand" ofType:@"json"];
    NSData *dataHot = [NSData dataWithContentsOfFile:pathHotBrand];
    NSError *hotError = nil;
    NSDictionary *hotDic = [NSJSONSerialization JSONObjectWithData:dataHot options:NSJSONReadingMutableContainers error:&hotError];
    RootClass *Rootclass = [RootClass modelWithDic:hotDic];
    [_marrCar addObject:Rootclass];
//    NSLog(@"%@", Rootclass.result.list);
    
    //FinderData
    NSString *path = [[NSBundle mainBundle] pathForResource:@"AllCar" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSError *error = nil;
   NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
   NSArray *arrayCar = dic[@"result"][@"brandlist"];
    for (NSDictionary *dicGroup in arrayCar) {
        GroupCarModel *groupModel = [[GroupCarModel alloc]init];
        groupModel.letter = dicGroup[@"letter"];
        for (NSDictionary *dic in dicGroup[@"list"]) {
            EachCarModel *Eachmodel = [EachCarModel eachCarModelWithDic:dic];
            [groupModel.list addObject:Eachmodel];
        }
        [_marrCar addObject:groupModel];
    }
    
    
}

#endif


#pragma mark -dataURL

- (void)createDataUrl
{
    _marrCar = [NSMutableArray array];
    NSURL *URLHotBrand = [NSURL URLWithString:@"http://cars.app.autohome.com.cn/dealer_v6.0.0/dealer/hotbrands-pm2.json"];
    NSMutableURLRequest *requestHot = [NSMutableURLRequest requestWithURL:URLHotBrand];
    requestHot.HTTPMethod = @"GET";
    NSURLSession *sessionHot = [NSURLSession sharedSession];
   NSURLSessionDataTask *hotDataTask = [sessionHot dataTaskWithRequest:requestHot completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
       dispatch_async(dispatch_get_main_queue(), ^{
           NSError *error = nil;
           NSDictionary *dicHot = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
           RootClass *rootClass = [RootClass modelWithDic:dicHot];
           [_marrCar addObject:rootClass];
           
           //  获取其他数据
           
           NSURL *urlAll = [NSURL URLWithString:@"http://app.api.autohome.com.cn/autov4.6/cars/brands-a2-pm2-v4.6.1-ts635580073583652962.html"];
           NSMutableURLRequest *AllRequest = [[NSMutableURLRequest alloc] initWithURL:urlAll];
           AllRequest.HTTPMethod = @"GET";
           NSURLSession *sessionAll = [NSURLSession sharedSession];
         NSURLSessionDataTask *dataTaskAll = [sessionAll dataTaskWithRequest:AllRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 NSError *error = nil;
                 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                 NSArray *arrayCar = dic[@"result"][@"brandlist"];
                 for (NSDictionary *dicGroup in arrayCar) {
                     GroupCarModel *groupModel = [[GroupCarModel alloc]init];
                     groupModel.letter = dicGroup[@"letter"];
                     for (NSDictionary *dic in dicGroup[@"list"]) {
                         EachCarModel *Eachmodel = [EachCarModel eachCarModelWithDic:dic];
                         [groupModel.list addObject:Eachmodel];
                     }
                     [_marrCar addObject:groupModel];
                 }

                 [_tableView reloadData];
             });
             
           }];
           [dataTaskAll resume];
           
           //结束请求
           
       });
       
    }];
    [hotDataTask resume];
    
    
    
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _marrCar.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else {
    GroupCarModel *Groupmodel = _marrCar[section];
    return Groupmodel.list.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        HotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"poolHot" forIndexPath:indexPath];
        RootClass *rootClass = _marrCar[indexPath.row];
        cell.rootClass = rootClass;
        return cell;
    }
    
    AllCarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"allCar" forIndexPath:indexPath];
    GroupCarModel *GroupModel = _marrCar[indexPath.section];
    EachCarModel *eachModel = GroupModel.list[indexPath.row];
    cell.eachModel = eachModel;
//    NSLog(@"%@", eachModel);
    return cell;
}

// 分区标题

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"热门";
    }
    GroupCarModel *model = _marrCar[section];
    
    return model.letter;
}

// 快速索引

- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *marr = [NSMutableArray array];
    [marr addObject:@"热"];
    if (_marrCar.count != 0) {
        
        NSMutableArray *marr1 = [NSMutableArray arrayWithArray:_marrCar];
        [marr1 removeObjectAtIndex:0];
        for (GroupCarModel *model in marr1) {
            [marr addObject: model.letter];
        }
    }
    return marr;
}

// cell 的高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 200;
    }
    return 60;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
